package com.ganbing518.trace.test.thread;

import com.ganbing518.trace.common.log.context.TraceContext;
import com.ganbing518.trace.common.log.util.TraceUtils;
import com.ganbing518.trace.thread.executor.TraceExecutor;
import com.ganbing518.trace.thread.executor.TraceExecutorService;
import com.ganbing518.trace.thread.executor.TraceExecutors;
import com.ganbing518.trace.thread.executor.TraceThreadPoolTaskExecutor;
import com.ganbing518.trace.thread.factory.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Description:
 *
 * @author gan bing
 * @version V1.0
 * @date 2018-05-24 18:47
 */
public class Application {

    private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) throws Exception {

        String traceId = TraceUtils.newTraceId();
        TraceContext.setTraceId(traceId);

        ExecutorService traceExecutor = TraceExecutors.newFixedThreadPool(1, new NamedThreadFactory("Fix-Executors"));

        traceExecutor.execute(() -> LOGGER.info(TraceContext.getTraceId()));
        TraceContext.setTraceId(TraceUtils.newTraceId());
        traceExecutor.execute(() -> LOGGER.info(TraceContext.getTraceId()));
        TraceContext.setTraceId(TraceUtils.newTraceId());
        traceExecutor.execute(() -> LOGGER.info(TraceContext.getTraceId()));
        TraceContext.setTraceId(TraceUtils.newTraceId());
        traceExecutor.execute(() -> LOGGER.info(TraceContext.getTraceId()));

        TraceThreadPoolTaskExecutor executor = new TraceThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(1);
        executor.setThreadFactory(new NamedThreadFactory("trace"));
        executor.setQueueCapacity(100);
        executor.initialize();

        String traceId1 = TraceUtils.newTraceId();
        TraceContext.setTraceId(traceId1);
        executor.execute(() -> LOGGER.info(TraceContext.getTraceId()));

        String traceId2 = TraceUtils.newTraceId();
        TraceContext.setTraceId(traceId2);
        executor.submit(() -> LOGGER.info(TraceContext.getTraceId()));

        String traceId3 = TraceUtils.newTraceId();
        TraceContext.setTraceId(traceId3);
        executor.execute(() -> LOGGER.info(TraceContext.getTraceId()));

        String traceId4 = TraceUtils.newTraceId();
        TraceContext.setTraceId(traceId4);
        executor.submit(() -> LOGGER.info(TraceContext.getTraceId()));

        Thread.sleep(1000);

        executor.shutdown();

        traceExecutor.shutdown();
    }
}
